package com.wlxk.base.mybatisplus.manager;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlxk.base.common.query.WlQuery;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：wlxk
 * @since ：2022/1/21 14:20
 */
public abstract class BaseManager<M extends BaseMapper<T>, T, Q extends WlQuery> extends ServiceImpl<M, T> {

    /**
     * 分页查询
     *
     * @param query 查询条件
     * @return 结果
     */
    public List<T> queryByPage(Q query) {
        if (null == query) {
            query = getQNewInstance();
        }
        Page<T> pageQuery = new Page<>(query.getCurrentPage(), query.getPageSize());
        Page<T> list = page(pageQuery, getQueryWrapper(query));
        query.setTotalRecord((int) list.getTotal());
        if (CollectionUtils.isEmpty(list.getRecords())) {
            return new ArrayList<>();
        }
        return list.getRecords();
    }

    /**
     * 查询-不分页
     *
     * @param query 查询条件
     * @return 结果
     */
    public List<T> query(Q query) {
        if (null == query) {
            query = getQNewInstance();
        }
        return list(getQueryWrapper(query));
    }

    /**
     * 获取一条
     *
     * @param query 入参
     * @return 结果
     */
    public T getOne(Q query) {
        return getOne(getQueryWrapper(query), false);
    }

    /**
     * 查询条件转换
     *
     * @param query 入参
     * @return 结果
     */
    public abstract Wrapper<T> getQueryWrapper(Q query);

    /**
     * 获取查询类实例
     *
     * @return 结果
     */
    private Q getQNewInstance() {
        Class<Q> entityClass =
                (Class<Q>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Q query = null;
        try {
            query = entityClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return query;
    }

}
